package com.cat.dataStructure03;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/number-of-excellent-pairs/
 * @create 2025/11/12 18:49
 * @since JDK17
 */

public class Solution49 {
    public long countExcellentPairs(int[] arr, int k) {
        long ans = 0;
        int n = arr.length;
        Set<Integer> set = Arrays.stream(arr).boxed().collect(Collectors.toSet());
        int cnt = 0;
        int[] nums = new int[set.size()];
        for (int x : set) {
            nums[cnt++] = Integer.bitCount(x);
        }
        Arrays.sort(nums);  // 排序
        for (int i = 0; i < cnt; i++) {
            if (nums[i] * 2 >= k) {  // 相同的情况
                ans++;
            }
            int l = i, r = cnt, mid, t = k - nums[i];
            while (l + 1 < r) {
                mid = l + r >> 1;
                if (nums[mid] >= t) {
                    r = mid;
                } else {
                    l = mid;
                }
            }
            ans += (cnt - r) * 2;
        }

        return ans;
    }
}